package cn.net.shuxing.yifu.common.service;

import cn.net.shuxing.yifu.common.constant.CodeConst;
import cn.net.shuxing.yifu.common.dto.BaseDto;
import cn.net.shuxing.yifu.common.util.JedisUtil;
import cn.net.shuxing.yifu.common.util.MailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class MailService {
    @Autowired
    private JedisUtil jedisUtil;

    public BaseDto sendMail(String receiveMail, String redisKey) {
        //Jedis //jedis = jedisUtil.getJedis();
        if ("1".equals(jedisUtil.get(redisKey + "timeout"))) {
            //jedisUtil.close();
            BaseDto baseDto = new BaseDto();
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg("1分钟内只能发送一封验证邮件");
            return baseDto;
        }
        Random random = new Random();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            builder.append(Math.abs(random.nextInt() % 10));
        }
        String code = builder.toString();

        try {
            if (MailUtil.sendMail(receiveMail, code)) {
                BaseDto baseDto = new BaseDto();
                baseDto.setData("验证邮件发送成功");
                jedisUtil.set(redisKey,code);
                jedisUtil.expire(redisKey,60 * 5 );
                jedisUtil.set(redisKey + "timeout","1");
                jedisUtil.expire(redisKey + "timeout" ,60 );
//                jedisUtil.setex(redisKey, 10, code);
//                jedisUtil.setex(redisKey + "timeout", 20, "1");
                //jedisUtil.close();
                return baseDto;
            } else {
                BaseDto baseDto = new BaseDto();
                baseDto.setCode(CodeConst.ERROR);
                baseDto.setMsg("验证邮件发送失败");
                //jedisUtil.close();
                return baseDto;
            }
        } catch (Exception e) {
            e.printStackTrace();
            BaseDto baseDto = new BaseDto();
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg("验证邮件发送失败");
            //jedisUtil.close();
            return baseDto;
        }

    }
}
